package com.supercwn.player.app.manager.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.AppCompatSeekBar;
import android.support.v7.widget.DefaultItemAnimator;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.supercwn.player.R;
import com.supercwn.player.app.manager.adapter.BaseRecyclerViewAdapter;
import com.supercwn.player.app.manager.adapter.BaseRecyclerViewHolder;
import com.supercwn.player.app.manager.bean.StorageBean;
import com.supercwn.player.app.manager.util.CleanFileManager;
import com.supercwn.player.app.manager.util.FocusAnimUtils;
import com.supercwn.player.app.manager.util.ReadAllAppUtil;
import com.supercwn.player.app.manager.view.FocusListenerLinearLayout;
import com.supercwn.player.app.manager.view.FocusRecyclerView;
import com.supercwn.player.app.manager.widget.FocusGridLayoutManager;
import com.supercwn.player.app.manager.widget.SpaceItemDecoration;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


/**
 * 项目名称：SuperPlayer-master
 * 类描述：
 * 创建人：TianGenhu
 * 创建时间：2017/12/8 14:19
 * 修改人：TianGenhu
 * 修改时间：2017/12/8 14:19
 * 修改备注：
 */

public class CleanFileManagerActivity2 extends Activity {

    private String TAG = "TGH";
    private static boolean BATCH_DELETE = false;
    private FocusRecyclerView gRecyclerView;
    private FocusGridLayoutManager fgLayoutManager;
    private SpaceItemDecoration itemDecoration;
    private MyAdapter mAdapter;
    private ReadAllAppUtil readAllApp;
    private TextView tvConut;//卸载个数
    private FocusListenerLinearLayout focusListenerLinearLayout;
    private AppCompatSeekBar seekBar;
    private TextView tvTips;
    private ImageView ivUninstall;
    private LinearLayout deleteBtn;
    private TextView percentTotalCapacity;
    private TextView surplusCapacity;
    private View mOldView;
    List<StorageBean> fileCompareThesize = new ArrayList<>();
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                upDateApp();
                upDateMemorySize();
            } else if (msg.what == 2) {
                mAdapter.notifyDataSetChanged();
            }

        }
    };

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_manager_activty_2);
        initView();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initView() {
        readAllApp = ReadAllAppUtil.getInstance(this);
        focusListenerLinearLayout = (FocusListenerLinearLayout) findViewById(R.id.layoutContent);
        focusListenerLinearLayout.setOnFocusSearchListener(focusSearchListener);
        focusListenerLinearLayout.setOnChildFocusChangeListener(focusChangeListener);

        //使用的容量百分比
        percentTotalCapacity = (TextView) findViewById(R.id.percent_total_capacity);
        seekBar = (AppCompatSeekBar) findViewById(R.id.seekBar);
        seekBar.setMax(100);

        //剩余容量数据
        surplusCapacity = (TextView) findViewById(R.id.surplus_capacity);
        tvTips = (TextView) findViewById(R.id.tvTips);
        tvConut = (TextView) findViewById(R.id.tvCount);
        ivUninstall = (ImageView) findViewById(R.id.imgUninstall);
        deleteBtn = (LinearLayout) findViewById(R.id.deleteBtn);
        deleteBtn.requestFocus();
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (BATCH_DELETE) {
                    if (mAdapter.getSelectedItems().size() > 0) {
                        //批量卸载代码
                        batchUninstallApp(mAdapter.getSelectedItems());
                    } else {
                        BATCH_DELETE = false;
                        ivUninstall.setImageDrawable(getResources().getDrawable(R.mipmap.delete_icon));
                        tvTips.setText("Tips:点击'垃圾桶'进入批量卸载模式");
                        mAdapter.notifyDataSetChanged();
                    }
                } else {
                    BATCH_DELETE = true;
                    ivUninstall.setImageDrawable(getResources().getDrawable(R.mipmap.delete_icon_selected));
                    tvTips.setText("Tips:点击显示绿色垃圾桶的item可以取消");
                    mAdapter.notifyDataSetChanged();
                    setFor();
                }
            }
        });


        gRecyclerView = (FocusRecyclerView) findViewById(R.id.gRecyclerView);
        fgLayoutManager = new FocusGridLayoutManager(this, 1);
        int spacingInPixels = 10/*getResources().getDimensionPixelSize(R.dimen.d_8dp)*/;
        itemDecoration = new SpaceItemDecoration(spacingInPixels);

        gRecyclerView.setLayoutManager(fgLayoutManager);
        gRecyclerView.addItemDecoration(itemDecoration);
        gRecyclerView.setScrollDy(220);
        gRecyclerView.setItemAnimator(new DefaultItemAnimator());

        mAdapter = new MyAdapter(this);
        gRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                toggleSelection(position);
            }

            @Override
            public void onItemLongClick(int position, Object data) {
                toggleSelection(position);
            }
        });

        mHandler.sendEmptyMessage(0);

    }


    private void upDateMemorySize() {
        //获取sdk的总大小
        String sdTotalSize = readAllApp.getSDTotalSize();
        //获取sdk的可用容量
        String sdAvailableSize = readAllApp.getSDAvailableSize();
        //获取机身内存的总大小
        String romTotalSize = readAllApp.getRomTotalSize();
        //获取机身可用内存大小
        String romAvailableSize = readAllApp.getRomAvailableSize();
        Log.i(TAG, "sdk总容量: " + sdTotalSize + "    sdk剩余容量  ：" + sdAvailableSize + "  机身总内存  ：" + romTotalSize + "   机身可用内存  ：" + romAvailableSize);

        if (!TextUtils.isEmpty(sdTotalSize)) {
            String s;
            String s1;
            s = sdTotalSize.split(" ")[0];

            if (!TextUtils.isEmpty(sdAvailableSize)) {
                s1 = sdAvailableSize.split(" ")[0];
            } else {//0
                s1 = "0";
            }

            double v1 = (Double.parseDouble(s) - Double.parseDouble(s1)) * 100d / Double.parseDouble(s);
            BigDecimal b = new BigDecimal(v1);
            double f1 = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
            Log.i(TAG, s + "   剩余空间  ： " + s1 + "     百分比  ：" + v1 + "      " + f1);
            if (!TextUtils.isEmpty(s) && !TextUtils.isEmpty(s1)) {
                seekBar.setProgress((int) f1);
                percentTotalCapacity.setText("占用" + f1 + "%");
            } else {
                seekBar.setProgress(0);
            }
        }

        surplusCapacity.setText("总共" + sdTotalSize + " 剩余" + sdAvailableSize);

    }

    private List<StorageBean> files;

    /**
     *
     */
    private void upDateApp() {
        File externalStorageDirectory = Environment.getExternalStorageDirectory();//获取外部存储目录即 SDCard
        files = CleanFileManager.listLinkedFiles(externalStorageDirectory + "/");

        Log.i(TAG, "文件的个数  ：" + files.size());
        //进行排序
        Collections.sort(files, new Comparator<StorageBean>() {
            @Override
            public int compare(StorageBean o1, StorageBean o2) {
                if (o1.getSize() > o2.getSize()) {
                    return -1;
                } else if (o1.getSize() < o2.getSize()) {
                    return 1;
                } else if (o1.getSize() == o2.getSize()) {
                    return 0;
                }
                return 0;
            }
        });

        //小于1兆的不要
        for (int i = 0; i < files.size(); i++) {
            StorageBean storageBean = files.get(i);
//                if (storageBean.getSize() > 1024 * 1024) {
            if (storageBean.getSize() > 0) {
                fileCompareThesize.add(storageBean);
            }
        }
        mAdapter.clearSelection();
        mAdapter.setData(fileCompareThesize);
        mAdapter.notifyDataSetChanged();
        Log.i(TAG, "过滤后的文件个数  ：" + fileCompareThesize.size());

    }

    /**
     * 切换item的选中状态，并刷新UI
     *
     * @param position
     */
    private void toggleSelection(int position) {
        View viewItem = fgLayoutManager.findViewByPosition(position);
        ImageView deletePic = null;
        if (BATCH_DELETE) {  //批量卸载状态
            mAdapter.toggleSelection(position);
            tvConut.setText(mAdapter.getSelectedItems().size() + "");
            //点击显示选中状态
            if (mAdapter.isSelected(position)) {
                if (viewItem != null) {
                    deletePic = (ImageView) viewItem.findViewById(R.id.deletePic);
                    deletePic.setImageDrawable(this.getResources().getDrawable(R.mipmap.delete_icon_selected));
                }
            } else {
                if (viewItem != null) {
                    deletePic = (ImageView) viewItem.findViewById(R.id.deletePic);
                    deletePic.setImageDrawable(this.getResources().getDrawable(R.mipmap.delete_icon));
                }
            }
        } else { //单个卸载状态，点击直接卸载
            uninstallApp(position);
        }
    }

    private void setFor() {
        if (fileCompareThesize != null) {
            for (int i = 0; i < fileCompareThesize.size(); i++) {
                toggleSelection(i);
            }
        }
    }


    /**
     * 单个卸载
     *
     * @param position
     */
    private void uninstallApp(int position) {
        StorageBean storageBean = fileCompareThesize.get(position);
        String url = storageBean.getUrl();
        CleanFileManager.deleteFolderFile(url, true);
        fileCompareThesize.remove(position);
        mAdapter.setData(fileCompareThesize);
        tvConut.setText("");
        mAdapter.clearSelection();
        tvConut.setText("");
        deleteBtn.requestFocus();
        mHandler.sendEmptyMessage(2);

        Log.i(TAG, "删除了一条  剩下条数 ：" + fileCompareThesize.size());
    }

    /**
     * 批量卸载
     *
     * @param appList
     */
    private void batchUninstallApp(List<Integer> appList) {
        for (int position : appList) {
            uninstallApp(position);
        }
    }

    private final FocusListenerLinearLayout.OnChildFocusChangeListener focusChangeListener = new FocusListenerLinearLayout.OnChildFocusChangeListener() {
        @Override
        public void focusChange(View oldView, View newView) {
            if (mOldView != null) {
                FocusAnimUtils.unFocusAnim(mOldView);
            }
            if (newView != null) {
                FocusAnimUtils.focusAnim(newView);
            }
            mOldView = newView;  //4.3以下版本需要自己保存上一次的焦点.
        }
    };

    private final FocusListenerLinearLayout.OnFocusSearchListener focusSearchListener = new FocusListenerLinearLayout.OnFocusSearchListener() {
        @Override
        public View onFocusSearch(View focused, int direction) {
            View res = null;
            switch (direction) {
                case View.FOCUS_DOWN:
                    break;
                case View.FOCUS_UP:
                    if (gRecyclerView.hasFocus()) {
                        res = focused;
                    }
                    break;
                case View.FOCUS_LEFT:
                    break;
                case View.FOCUS_RIGHT:
                    break;
            }
            return res;
        }
    };


    static class MyAdapter extends BaseRecyclerViewAdapter<StorageBean> {
        private Context mContext;//List<StorageBean> fileCompareThesize

        public MyAdapter(Context mContext) {
            this.mContext = mContext;
        }

        /**
         * 创建item view
         *
         * @param parent
         * @param viewType
         * @return
         */
        @Override
        protected BaseRecyclerViewHolder createItem(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_app_manager_2, null);
            MyAdapter.AppViewHolder viewHolder = new MyAdapter.AppViewHolder(view);
            viewHolder.appIcon = (TextView) view.findViewById(R.id.appIcon);
            viewHolder.appName = (TextView) view.findViewById(R.id.appName);
            viewHolder.appVersion = (TextView) view.findViewById(R.id.appVersion);
            viewHolder.deletePic = (ImageView) view.findViewById(R.id.deletePic);
            viewHolder.appSize = (TextView) view.findViewById(R.id.appSize);
            return viewHolder;
        }

        /**
         * 绑定数据
         *
         * @param holder
         * @param position
         */
        @Override
        protected void bindData(BaseRecyclerViewHolder holder, int position) {
            ((MyAdapter.AppViewHolder) holder).appIcon.setText(position + 1 + "");
            ((MyAdapter.AppViewHolder) holder).appName.setText(getItemData(position).getUrl());
            ((MyAdapter.AppViewHolder) holder).appVersion.setText("版本:" + getItemData(position).getTime());
            ((MyAdapter.AppViewHolder) holder).appSize.setText(CleanFileManager.getFormatSize(getItemData(position).getSize()));
            ((MyAdapter.AppViewHolder) holder).deletePic.setImageDrawable(isSelected(position) ? getDrawableById(R.mipmap.delete_icon_selected) : getDrawableById(R.mipmap.delete_icon));
            ((MyAdapter.AppViewHolder) holder).deletePic.setVisibility(BATCH_DELETE ? View.VISIBLE : View.GONE);
        }

        static class AppViewHolder extends BaseRecyclerViewHolder {
            View mView;
            ImageView deletePic;
            TextView appName, appVersion, appSize, appIcon;

            public AppViewHolder(View itemView) {
                super(itemView);
                mView = itemView;
            }

            @Override
            protected View getView() {
                return mView;
            }
        }

        private Drawable getDrawableById(int id) {
            return mContext.getResources().getDrawable(id);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BATCH_DELETE = false;
    }

}
